package com.sanq.product.controller;

import com.sanq.product.config.utils.annotation.LogAnnotation;
import com.sanq.product.config.utils.entity.Response;
import com.sanq.product.config.utils.string.MatcherUtil;
import com.sanq.product.config.utils.string.ShareCodeUtil;
import com.sanq.product.config.utils.string.StringUtil;
import com.sanq.product.redis.service.JedisPoolService;
import com.sanq.product.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.ws.RequestWrapper;
import java.util.Map;

/**
 * com.sanq.product.controller.SmsController
 *
 * @author sanq.Yan
 * @date 2019/7/21
 */
@RestController
@RequestMapping("/api/sms")
public class SmsController {

    @Resource
    private JedisPoolService jedisPoolService;
    @Value("${sms.tel}")
    public String sendAdminTel;
    @Resource
    private SmsUtil smsUtil;

    @LogAnnotation(description = "发送验证码")
    @GetMapping(value = "/send")
    public Response sendSmsCode(HttpServletRequest request, String tel) {

        String key = String.format("sms:%s", tel);

        if(jedisPoolService.exists(key)) {
            return new Response().failure("操作的太频繁了， 请稍后再试");
        }

        if(StringUtil.isEmpty(tel)) {
            return new Response().failure("手机号不能为空");
        }

        if(!MatcherUtil.isTelephone(tel)) {
            return new Response().failure("请输入正确格式的手机号");
        }

        int code = ShareCodeUtil.code();

        Map<String, String> map = smsUtil.sendSms(tel, code + "");

        if("0".equals(map.get("result"))) {
            jedisPoolService.set(key, code + "", 5 * 60);
//            if(!StringUtil.isEmpty(map.get("balance")) && 10 <= StringUtil.toInteger(map.get("balance"))) {
//                smsUtil.sendSms(sendAdminTel, "000000");
//            }
            return new Response().success("发送成功");
        }

        return new Response().failure(map.get("description"));
    }

}
